package com.topway.dsmflex.ui.composite.synchro;

import java.io.IOException;
import java.util.List;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.DialogCellEditor;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.jdom.JDOMException;

import com.Consts;
import com.swtdesigner.SWTResourceManager;
import com.topway.dsmflex.Alert;
import com.topway.dsmflex.Log;
import com.topway.dsmflex.model.synchro.DataColumnBean;
import com.topway.dsmflex.model.synchro.DataSqlBean;
import com.topway.dsmflex.services.synchro.SqlServices;
import com.topway.dsmflex.ui.contentProvider.TableContentProvider;
import com.topway.dsmflex.ui.dialog.ExpressionDialog;
import com.topway.dsmflex.util.XmlEditUtil;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;

public class AddSqlSynchro extends Dialog {

	protected Object result;
	protected Shell shell;
	private Table table;
	private Text txtName;
	private DataSqlBean tableBean;

	
	   private ComboBoxCellEditor comTargetColumnName;
	   private String [] targetTables  = new String[]{};
	   private String [] targetColumns  = new String[]{};
	   private String [] targetSource = new String[]{};
	   
	   private SqlServices sqlServices = null;
	   
	   
	   private Combo cboSourceSource;
	   private 	StyledText txtSourceSql;
	   private 	Combo cboTargetSource;
	   private 	Combo cboOperator;
	   private 	StyledText txtCurrentSourceSql;
	   private StyledText txtCurrentTargetSql;
	   private 	StyledText txtTargetExecuteSql;
	   private 	StyledText txtUpdateSourceSql;
	   private StyledText txtBeforeTargetSql;
	   private 	Combo cboTargetTable;
	   private Text txtNterval;
	   private TableViewer tvInputMeta;
	   private Button checkEnabled;
	   
	   private boolean flag= false;
	   private String btnType = "";
	/**
	 * Create the dialog.
	 * @param parentble
	 * @param style
	 */
	public AddSqlSynchro(Shell parent, int style,DataSqlBean tableBean) {
		super(parent, style);
		this.tableBean = tableBean;
	}

	   public int initForm() {
		   this.sqlServices = SqlServices.getSqlServices();
		      try {
		    	  targetSource = XmlEditUtil.getDataSources();
				} catch (JDOMException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
		      cboOperator.setItems(Consts.TABLE_OPERATOR);
			   cboSourceSource.setItems(targetSource);
			   cboTargetSource.setItems(targetSource);
				if(null==tableBean)
				{
					flag = true;
					shell.setText("添加sql配置");
					this.tableBean = new DataSqlBean("sql");
				}
				else
				{
					InitDataTableBean();
					shell.setText("修改sql配置["+tableBean.getName()+"]");
				}
				   if(shell.getText().equals("添加sql配置"))
				   {
					   cboOperator.select(1);
					   cboSourceSource.select(0);
					   cboTargetSource.select(0);	
				   }
				 return 1;
	   }
	/**
	 * Open the dialog.
	 * @return the result
	 */
	public Object open() {
		createContents();
		
		initForm();
		shell.open();
		shell.layout();
		Display display = getParent().getDisplay();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		return tableBean;
	}

	/**
	 * Create contents of the dialog.
	 */
	private void createContents() {
	    shell = new Shell(getParent(),SWT.CLOSE | SWT.TITLE  );
		shell.setSize(539, 488);
		shell.setLayout(new FillLayout(SWT.HORIZONTAL));
	    shell.setLocation(getParentLocation());
	    
		SashForm sashForm = new SashForm(shell, SWT.VERTICAL);
		
		Group grpSql = new Group(sashForm, SWT.NONE);
		grpSql.setLayout(null);
		
		Label lblName = new Label(grpSql, SWT.NONE);
		lblName.setBounds(92, 23, 36, 12);
		lblName.setText("名称：");
		
		txtName = new Text(grpSql, SWT.BORDER);
		txtName.setBounds(134, 20, 184, 18);
		
		Label label = new Label(grpSql, SWT.NONE);
		label.setBounds(68, 54, 60, 12);
		label.setText("源数据源：");
		
		cboSourceSource = new Combo(grpSql, SWT.NONE);
		cboSourceSource.setBounds(134, 51, 124, 20);
		cboSourceSource.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				if(null==cboSourceSource.getText()||cboSourceSource.getText().equals(""))return;
				tableBean.setDsSource(cboSourceSource.getText());
			}
		});
		
		
		 txtSourceSql = new StyledText(grpSql, SWT.BORDER|SWT.V_SCROLL);
		 txtSourceSql.setToolTipText("可引用［前行(标)］中的结果，{列}，默认大写，注意：必需先设置完列后，再引用变量");
		 txtSourceSql.setBounds(134, 82, 347, 56);
//		 txtSourceSql.setFont(SWTResourceManager.getFont("Fixedsys", 10, SWT.NONE));
		Label label_1 = new Label(grpSql, SWT.NONE);
		label_1.setBounds(68, 92, 60, 12);
		label_1.setText("查询语句：");
		
	
		cboTargetSource = new Combo(grpSql, SWT.NONE);
		cboTargetSource.setBounds(339, 51, 142, 20);
		cboTargetSource.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				if(null!=cboTargetSource&&!cboTargetSource.getText().equals(""))
				{
					tableBean.setDsTarget(cboTargetSource.getText());
					targetTables =  sqlServices.getTargetTablesByDb(tableBean);
					cboTargetTable.setItems(targetTables);
				}
			}
		});
		
		Label label_2 = new Label(grpSql, SWT.NONE);
		label_2.setBounds(264, 54, 72, 12);
		label_2.setText("目标数据源：");
		
		Label label_3 = new Label(grpSql, SWT.NONE);
		label_3.setBounds(331, 151, 60, 12);
		label_3.setText("目标操作：");
		

		cboOperator = new Combo(grpSql, SWT.NONE);
		cboOperator.setBounds(397, 148, 84, 20);
		
		Label label_7 = new Label(grpSql, SWT.NONE);
		label_7.setBounds(79, 147, 48, 12);
		label_7.setText("目标表：");
		

		
		cboTargetTable = new Combo(grpSql, SWT.NONE);
		cboTargetTable.setBounds(133, 148, 192, 20);
		cboTargetTable.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent arg0) {
				if(null!=cboTargetTable&&!cboTargetTable.getText().equals(""))
				{
					tableBean.setTableNameTarget(cboTargetTable.getText());
				}
			}
		});
		
		Label label_8 = new Label(grpSql, SWT.NONE);
		label_8.setBounds(336, 24, 36, 12);
		label_8.setText("频率：");
		
		Button button = new Button(grpSql, SWT.NONE);
		button.setBounds(168, 182, 60, 22);
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
			}
		});
		button.setText("查询");
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if(null!=tableBean.getDsSource())
				{
					tableBean.setSelectSourceSql(txtSourceSql.getText());
					if(null==tableBean.getSelectSourceSql()||tableBean.getSelectSourceSql().equals(""))
						return;
		            try {
		            	List<DataColumnBean> list = tableBean.getDataColumnBean();
		            //	if(null==list||list.size()==0)//不读从数据库中获取最新的字段信息
		            		list = (List<DataColumnBean>) sqlServices.getColumnInfo(tableBean);
		            	
		            	targetColumns =  sqlServices.getColumnInfoArray(tableBean);
					    	  comTargetColumnName.setItems(targetColumns);
					      
					      if(!tableBean.getTableNameSource().equals(tableBean.getTableNameTarget()))
					      {
					    	  for (DataColumnBean _dc : list) {
					    		  for (int i = 0; i < targetColumns.length; i++) {
					    			  if(_dc.getColumnNameTarget().equals(targetColumns[i]))
					    			  {
					    				  _dc.setColumnNameTarget(targetColumns[i]);
					    				  break;
					    			  }else if(!_dc.getColumnNameTarget().equals("")&& !_dc.getColumnNameTarget().equals(targetColumns[i]))
					    			  {
					    				 break;
					    			  }else
					    				  _dc.setColumnNameTarget("");
									}  
					    	  }
					      }
					      
		            	tvInputMeta.setInput(list);
					} catch (Exception ee) {
						ee.printStackTrace();
						Log.error(ee.getMessage());
					}	
					
				}
			}
		});
		
		Button btnNewButton = new Button(grpSql, SWT.NONE);
		btnNewButton.setBounds(256, 182, 71, 22);
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				btnType="SUBMIT";
				int reuslt = SaveDataTableBean();
				if(reuslt>0)
				shell.close();
			}

		});
		btnNewButton.setText("确定");
		
		txtNterval = new Text(grpSql, SWT.BORDER);
		txtNterval.setBounds(378, 21, 60, 18);
		txtNterval.setText("10.0");
		
		Label label_9 = new Label(grpSql, SWT.NONE);
		label_9.setText("（分）");
		label_9.setBounds(445, 24, 36, 12);
		
		Button btnNewButton_1 = new Button(grpSql, SWT.NONE);
		btnNewButton_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
					tableBean=null;
					shell.close();
			}
		});
		btnNewButton_1.setBounds(352, 182, 72, 22);
		btnNewButton_1.setText("取消");
		
		checkEnabled = new Button(grpSql, SWT.CHECK);
		checkEnabled.setSelection(true);
		checkEnabled.setBounds(69, 188, 93, 16);
		checkEnabled.setText("激活");
		
		TabFolder tabFolder = new TabFolder(sashForm, SWT.NONE);
		
		TabItem tbtmNewItem_4 = new TabItem(tabFolder, SWT.NONE);
		tbtmNewItem_4.setText("前行(目标)");
		
		txtBeforeTargetSql = new StyledText(tabFolder, SWT.BORDER);
		tbtmNewItem_4.setControl(txtBeforeTargetSql);
		
		TabItem tbtmNewItem = new TabItem(tabFolder, SWT.NONE);
		tbtmNewItem.setText("并行(源)");
		
		
		txtCurrentSourceSql = new StyledText(tabFolder, SWT.BORDER|SWT.V_SCROLL);
		txtCurrentSourceSql.setToolTipText("可引用［查询语句］中的结果，{列}，默认大写");
		tbtmNewItem.setControl(txtCurrentSourceSql);
		
		TabItem tbtmNewItem_3 = new TabItem(tabFolder, SWT.NONE);
		tbtmNewItem_3.setText("并行(目标)");
		
				 txtCurrentTargetSql = new StyledText(tabFolder, SWT.BORDER|SWT.V_SCROLL);
				 txtCurrentTargetSql.setToolTipText("可引用［查询语句］中的结果，{列}，默认大写");
				 tbtmNewItem_3.setControl(txtCurrentTargetSql);
				 
				 TabItem tbtmNewItem_2 = new TabItem(tabFolder, SWT.NONE);
				 tbtmNewItem_2.setText("后行(源)");
				 

				 
				 txtUpdateSourceSql = new StyledText(tabFolder, SWT.BORDER|SWT.V_SCROLL);
				 txtUpdateSourceSql.setToolTipText("可引用［查询语句］中的结果，{列}，默认大写");
				 tbtmNewItem_2.setControl(txtUpdateSourceSql);
				 
				 TabItem tbtmNewItem_1 = new TabItem(tabFolder, SWT.NONE);
				 tbtmNewItem_1.setText("后行(目标)");
				 

				 
				 txtTargetExecuteSql = new StyledText(tabFolder, SWT.BORDER|SWT.V_SCROLL);
				 txtTargetExecuteSql.setToolTipText("可引用［查询语句］中的结果，{列}，默认大写");
				 tbtmNewItem_1.setControl(txtTargetExecuteSql);
		
		tvInputMeta = new TableViewer(sashForm, SWT.BORDER | SWT.FULL_SELECTION);
	      tvInputMeta.setContentProvider(new TableContentProvider());
	      tvInputMeta.setLabelProvider(new InputMetaLabelProvider());
	      tvInputMeta.setColumnProperties(INPUTMETAS);
	      Table tblInputMeta = tvInputMeta.getTable();
	     
			
	      tblInputMeta.setLinesVisible(true);
	      tblInputMeta.setHeaderVisible(true);
	      CellEditor[] cellEditor2 = new CellEditor[4];
	      cellEditor2[0] = new TextCellEditor(tblInputMeta, SWT.READ_ONLY);
	      cellEditor2[1] = new ComboBoxCellEditor(tblInputMeta,Consts.TABLE_KEY_LABEL, SWT.READ_ONLY);
	      comTargetColumnName = new ComboBoxCellEditor(tblInputMeta,targetColumns, SWT.READ_ONLY);
	      cellEditor2[2] =comTargetColumnName;
	      cellEditor2[3] = new ExpressionCellEditor(tblInputMeta);
	      
	      tvInputMeta.setCellEditors(cellEditor2);
	      tvInputMeta.setCellModifier(new InputsCellModifier(tvInputMeta));

	      final TableColumn colNameSource = new TableColumn(tblInputMeta, SWT.NONE);
	      colNameSource.setWidth(110);
	      colNameSource.setText("源字段名");

	      final TableColumn colIsKey = new TableColumn(tblInputMeta, SWT.NONE);
	      colIsKey.setWidth(70);
	      colIsKey.setText("主键");

	      final TableColumn colNameTarget = new TableColumn(tblInputMeta, SWT.NONE);
	      colNameTarget.setWidth(110);
	      colNameTarget.setText("目标字段名");
	      
		    final TableColumn colExpress = new TableColumn(tblInputMeta, SWT.NONE);
		    colExpress.setWidth(150);
		    colExpress.setText("表达式");
		    sashForm.setWeights(new int[] {216, 100, 141});
		    
		    
		    
		    shell.addShellListener(new ShellAdapter() {
	            public void shellClosed(ShellEvent e) {
	            	if(btnType.equals(""))
	            	tableBean = null;
						e.doit=true;
	            }
		    });
		    

	}
	
	private void InitDataTableBean()
	{

		this.txtName.setText(null==this.tableBean.getName()?"":this.tableBean.getName());
//		this.tableBean.getSourceDataSource(null);
//		this.tableBean.getTargetDataSource(null);
		cboSourceSource.setText(this.tableBean.getDsSource());
		cboTargetSource.setText(this.tableBean.getDsTarget());
		txtSourceSql.setText(this.tableBean.getSelectSourceSql());
		cboTargetTable.setText(this.tableBean.getTableNameTarget());
		checkEnabled.setSelection(this.tableBean.getEnabled()==1);
		cboOperator.setText(null==this.tableBean.getOperatorTarget()?"":this.tableBean.getOperatorTarget());
		txtCurrentSourceSql.setText(null==this.tableBean.getCurrentSourceSql()?"":this.tableBean.getCurrentSourceSql());
		txtCurrentTargetSql.setText(null==this.tableBean.getCurrentTargetSql()?"":this.tableBean.getCurrentTargetSql());
		txtUpdateSourceSql.setText(null==this.tableBean.getUpdateSourceSql()?"":this.tableBean.getUpdateSourceSql());
		txtTargetExecuteSql.setText(null==this.tableBean.getTargetExecuteSql()?"":this.tableBean.getTargetExecuteSql());
		txtBeforeTargetSql.setText(null==this.tableBean.getBeforeTargetSql()?"":this.tableBean.getBeforeTargetSql());
		txtNterval.setText(""+this.tableBean.getSynchroNterval());
		tvInputMeta.setInput(this.tableBean.getDataColumnBean());
		
	}
	   public Point getParentLocation() {

		      Shell shell = getParent();
		      int x = shell.getLocation().x;
		      int y = shell.getLocation().y;
		      Rectangle rectParent = shell.getBounds();
		      Point size = this.shell.getSize();
		      int xx = x + rectParent.width / 2 - size.x / 2;
		      int yy = y + rectParent.height / 2 - size.y / 2;
		      return new Point(xx, yy);
		   }
	   
	   
	public int SaveDataTableBean()
	{
		this.tableBean.setName(this.txtName.getText());
		this.tableBean.setSelectSourceSql(txtSourceSql.getText());
		this.tableBean.setOperatorTarget(cboOperator.getText());
		this.tableBean.setTableNameTarget(cboTargetTable.getText());
		this.tableBean.setCurrentSourceSql(txtCurrentSourceSql.getText());
		this.tableBean.setCurrentTargetSql(txtCurrentTargetSql.getText());
		this.tableBean.setUpdateSourceSql(txtUpdateSourceSql.getText());
		this.tableBean.setTargetExecuteSql(txtTargetExecuteSql.getText());
		this.tableBean.setEnabled(checkEnabled.getSelection()?1:0);
		this.tableBean.setBeforeTargetSql(txtBeforeTargetSql.getText());
		try {
			this.tableBean.setSynchroNterval(Float.valueOf(txtNterval.getText()));
		} catch (Exception e) {
			Alert.MsgBox("提示", "频率有误，请检查！");
			txtNterval.forceFocus();
			return 0;
		}
		if(null==tableBean.getName()||tableBean.getName().equals(""))
		{
			Alert.MsgBox("提示", "任务名必填，请检查！");
			txtName.forceFocus();
			return 0;
		}
		this.tableBean.setDataColumnBean((List<DataColumnBean>) tvInputMeta.getInput());
		return 1;
		
	}
	
	
	   public static String[] INPUTMETAS = new String[] { "columnNameSource","isKey" ,"columnNameTarget","colExpress"};
	   public static String[] TABLE_INPUTMETAS = new String[] { "check","sourceSource","selectSourceSql", "operatorTarget", "updateSourceSql","tableNameTarget","targetSource","targetExecuteSql","currentSourceSql","currentTargetSql","synchroNterval"};
	  


	   class InputsCellModifier implements ICellModifier {
	      private TableViewer tv;

	      public InputsCellModifier(TableViewer tv) {
	         this.tv = tv;
	      }

	      public boolean canModify(Object element, String property) {
	         return true;
	      }

	      public Object getValue(Object element, String property) {
	    	  DataColumnBean o = (DataColumnBean ) element;
	        if (property.equals("isKey")) return getIndex(Consts.TABLE_KEY, o.getIsKey());
	        else if (property.equals("columnNameSource")) return o.getColumnNameSource();
	        else if (property.equals("columnNameTarget"))  return getIndex(targetColumns, o.getColumnNameTarget()); 
	        else if (property.equals("colExpress")) return (null==o.getColExpress()?"":o.getColExpress());
	        throw new RuntimeException("错误的列别名:" + property);
	      }

	      private int getIndex(String[] labels, String name) {
	         for (int i = 0; i < labels.length; i++) {
	            if (labels[i].equalsIgnoreCase(name)) return i;
	         }
	         return 0;
	      }

	      public void modify(Object element, String property, Object value) {
	         TableItem item = (TableItem) element;
	         DataColumnBean o = (DataColumnBean ) item.getData();
	          if (property.equals("isKey")) {
		            o.setIsKey(Consts.TABLE_KEY[(Integer) value]);
		         }
	         else  if (property.equals("columnNameSource")) {
		            o.setColumnNameSource((String) value);
			     }
	         else  if (property.equals("columnNameTarget")) {
		        		 o.setColumnNameTarget(targetColumns[(Integer) value]);
	        	}
	         else  if (property.equals("colExpress")) {
		            o.setColExpress((String) value);
			     }
	         else {
	             throw new RuntimeException("错误的列别名:" + property);
	          }
	         tv.update(o, null);
	      }
	   }
	   
	   class InputMetaLabelProvider extends LabelProvider implements ITableLabelProvider {
		      public String getColumnText(Object obj, int columnIndex) {
		    	  DataColumnBean dsi = (DataColumnBean )  obj;
		         switch (columnIndex) {
		         case 0:
		            return dsi.getColumnNameSource();
		         case 1:
		        	 return getLabel(Consts.TABLE_KEY_LABEL,Consts.TABLE_KEY,dsi.getIsKey());
		         case 2:
		        	 return dsi.getColumnNameTarget();
		         case 3:
		        	 return dsi.getColExpress();
		         }
		         return null;
		      }
		      
		      private String getLabel(String[] labels, String[] values, String name) {
		         for (int i = 0; i < values.length; i++) {
		            if (values[i].equalsIgnoreCase(name)) return labels[i];
		         }
		         return "";
		      }

		      public String getText(Object element) {
		         return element == null ? "" : element.toString();
		      }

		      public Image getColumnImage(Object obj, int index) {
		         return null;
		      }
		   }

	   
	   class ExpressionCellEditor extends DialogCellEditor {

		      private Table table;

		      public ExpressionCellEditor(Composite parent) {
		         super(parent);
		         this.table = (Table) parent;
		      }
		      protected Object openDialogBox(Control cellEditorWindow) {
		         TableItem[] selectItems = table.getSelection();
		         String exp = "";
		         if (selectItems != null && selectItems.length > 0) exp = ((DataColumnBean) selectItems[0].getData()).getColExpress();
		         ExpressionDialog gcd = new ExpressionDialog(cellEditorWindow.getShell(), null==exp?"":exp);
		         String res = gcd.open();
		         return res;
		      }
		   }
}
